using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//


using DotNetNuke.UI.Utilities;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Definitions;
using DotNetNuke.Application;
using DotNetNuke.Entities.Host;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Portals;
using System.Web;
using DotNetNuke.Entities.Users;
using DotNetNuke.Common.Utilities;

namespace DotNetNuke.UI.ControlPanel
{

	partial class AddModule : System.Web.UI.UserControl, DotNetNuke.Web.UI.WebControls.IDnnRibbonBarTool
	{

		#region "Event Handlers"

		protected void AddNewOrExisting_OnClick(System.Object sender, System.EventArgs e)
		{
			LoadAllLists();
		}

		protected void PaneLst_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			LoadPositionList();
			LoadPaneModulesList();
			//Dim script As String = String.Format(glbScriptFormat, ResolveUrl("~/Resources/ControlPanel/ControlPanel.js"))
			//ClientAPI.RegisterStartUpScript(Page, "controlPanel", script)
		}

		protected void PageLst_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			LoadModuleList();
		}

		protected void PositionLst_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			PaneModulesLst.Enabled = PositionLst.SelectedValue == "ABOVE" || PositionLst.SelectedValue == "BELOW";
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			//For Pane Highlighting: Resources/ControlPanel/ControlPanel.js
			//jQuery.RequestRegistration()
			//Dim scriptUrl As String = ResolveUrl("~/Resources/ControlPanel/ControlPanel.js")
			//Page.ClientScript.RegisterClientScriptInclude("ControlPanel_AddModule", scriptUrl)
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			cmdAddModule.Click += new EventHandler(cmdAddModule_Click);
			AddNewModule.CheckedChanged += new EventHandler(AddNewOrExisting_OnClick);
			AddExistingModule.CheckedChanged += new EventHandler(AddNewOrExisting_OnClick);
			ModuleLst.SelectedIndexChanged += new Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventHandler(ModuleLst_SelectedIndexChanged);
			PageLst.SelectedIndexChanged += new Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventHandler(PageLst_SelectedIndexChanged);
			PaneLst.SelectedIndexChanged += new Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventHandler(PaneLst_SelectedIndexChanged);
			PositionLst.SelectedIndexChanged += new Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventHandler(PositionLst_SelectedIndexChanged);
			
			try
			{
				if ((Visible))
				{
					cmdAddModule.Enabled = Enabled;
					AddExistingModule.Enabled = Enabled;
					AddNewModule.Enabled = Enabled;
					Title.Enabled = Enabled;
					PageLst.Enabled = Enabled;
					ModuleLst.Enabled = Enabled;
					VisibilityLst.Enabled = Enabled;
					PaneLst.Enabled = Enabled;
					PositionLst.Enabled = Enabled;
					PaneModulesLst.Enabled = Enabled;
				}

				if ((!IsPostBack && Visible && Enabled))
				{
					LoadAllLists();
				}
				//Module failed to load
			}
			catch (Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
		}

		protected void cmdAddModule_Click(object sender, System.EventArgs e)
		{
			if (TabPermissionController.CanAddContentToPage() && CanAddModuleToPage())
			{
				int permissionType = 0;
				try
				{
					permissionType = int.Parse(VisibilityLst.SelectedValue);
				}
				catch (Exception ex)
				{
					permissionType = 0;
				}

				int position = -1;
				switch (PositionLst.SelectedValue)
				{
					case "TOP":
						position = 0;
						break;
					case "ABOVE":
						if (!string.IsNullOrEmpty(PaneModulesLst.SelectedValue))
						{
							try
							{
								position = int.Parse(PaneModulesLst.SelectedValue) - 1;
							}
							catch (Exception ex)
							{
								position = -1;
							}
						}
						else
						{
							position = 0;
						}
						break;
					case "BELOW":
						if (!string.IsNullOrEmpty(PaneModulesLst.SelectedValue))
						{
							try
							{
								position = int.Parse(PaneModulesLst.SelectedValue) + 1;
							}
							catch (Exception ex)
							{
								position = -1;
							}
						}
						else
						{
							position = -1;
						}
						break;
					case "BOTTOM":
						position = -1;
						break;
				}

				int moduleLstID = -1;
				try
				{
					moduleLstID = int.Parse(ModuleLst.SelectedValue);
				}
				catch (Exception ex)
				{
					moduleLstID = -1;
				}

				if ((moduleLstID > -1))
				{
					if ((AddExistingModule.Checked))
					{
						int pageID = -1;
						try
						{
							pageID = int.Parse(PageLst.SelectedValue);
						}
						catch (Exception ex)
						{
							pageID = -1;
						}

						if ((pageID > -1))
						{
							DoAddExistingModule(moduleLstID, pageID, PaneLst.SelectedValue, position, "", chkCopyModule.Checked);
						}
					}
					else
					{
						DoAddNewModule(Title.Text, moduleLstID, PaneLst.SelectedValue, position, permissionType, "");
					}
				}

				Response.Redirect(Request.RawUrl, true);
			}
		}


		protected void ModuleLst_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			ModuleController moduleCtrl = new ModuleController();
			SetCopyModuleMessage(GetIsPortable(moduleCtrl, ModuleLst.SelectedValue, PageLst.SelectedValue));

		}

		#endregion

		#region "Properties"

		public string ToolName
		{
			get { return "QuickAddModule"; }
			set
			{
				throw new NotSupportedException("Set ToolName not supported");
			}
		}

		public override bool Visible
		{
			get { return base.Visible == true && TabPermissionController.CanAddContentToPage(); }
			set { base.Visible = value; }
		}

		private bool _Enabled = true;
		public bool Enabled
		{
			get { return _Enabled && CanAddModuleToPage(); }
			set { _Enabled = value; }
		}

		#endregion

		#region "Methods"

		private void SetCopyModuleMessage(bool isPortable)
		{
			if ((isPortable))
			{
				chkCopyModule.Text = Localization.GetString("CopyModuleWcontent", this.LocalResourceFile);
				chkCopyModule.ToolTip = Localization.GetString("CopyModuleWcontent.ToolTip", this.LocalResourceFile);
			}
			else
			{
				chkCopyModule.Text = Localization.GetString("CopyModuleWOcontent", this.LocalResourceFile);
				chkCopyModule.ToolTip = Localization.GetString("CopyModuleWOcontent.ToolTip", this.LocalResourceFile);
			}
		}

		private void LoadAllLists()
		{
			LoadPageList();
			LoadModuleList();
			LoadVisibilityList();
			LoadPaneList();
			LoadPositionList();
			LoadPaneModulesList();
		}

		private void LoadPageList()
		{
			PageListTR.Visible = AddExistingModule.Checked;
			TitleTR.Visible = !AddExistingModule.Checked;
			chkCopyModule.Visible = AddExistingModule.Checked;

			if ((AddExistingModule.Checked))
			{
				chkCopyModule.Text = Localization.GetString("CopyModuleDefault.Text", this.LocalResourceFile);
			}


			PageLst.Items.Clear();
			if ((PageListTR.Visible))
			{
				PageLst.DataValueField = "TabID";
				PageLst.DataTextField = "IndentedTabName";
				PageLst.DataSource = TabController.GetPortalTabs(PortalSettings.Current.PortalId, PortalSettings.Current.ActiveTab.TabID, true, "", true, false, false, false, true);
				PageLst.DataBind();
			}
		}

		private void LoadModuleList()
		{
			if ((AddExistingModule.Checked))
			{
				//Get list of modules for the selected tab
				ModuleLst.Items.Clear();
				if ((!string.IsNullOrEmpty(PageLst.SelectedValue)))
				{
					ModuleController moduleCtrl = new ModuleController();
					ArrayList pageModules = new ArrayList();

					Dictionary<int, ModuleInfo> portalModules = moduleCtrl.GetTabModules(int.Parse(PageLst.SelectedValue));
					foreach (ModuleInfo m in portalModules.Values)
					{
						if (ModulePermissionController.CanAdminModule(m) == true && m.IsDeleted == false)
						{
							pageModules.Add(m);
						}
					}
					ModuleLst.DataValueField = "ModuleID";
					ModuleLst.DataTextField = "ModuleTitle";
					ModuleLst.DataSource = pageModules;
					ModuleLst.DataBind();

					if ((ModuleLst.Items.Count > 0))
					{
						chkCopyModule.Visible = true;
						SetCopyModuleMessage(GetIsPortable(moduleCtrl, ModuleLst.Items[0].Value, PageLst.SelectedValue));
					}

				}
			}
			else
			{
				ModuleLst.Items.Clear();
				ModuleLst.DataValueField = "DesktopModuleID";
				ModuleLst.DataTextField = "FriendlyName";
				ModuleLst.DataSource = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId).Values;
				ModuleLst.DataBind();

				//Select default module
				int defaultModuleID = -1;
				string defaultModuleName = Localization.GetString("DefaultModule", LocalResourceFile, PortalSettings.Current, null, true);
				if ((!string.IsNullOrEmpty(defaultModuleName)))
				{
					DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(defaultModuleName, PortalSettings.Current.PortalId);
					if (desktopModule != null && ModuleLst.Items.FindItemByValue(desktopModule.DesktopModuleID.ToString()) != null)
					{
						ModuleLst.SelectedValue = desktopModule.DesktopModuleID.ToString();
					}
				}
			}

			ModuleLst.Enabled = ModuleLst.Items.Count > 0;
		}


		private bool GetIsPortable(ModuleController moduleCtrl, string ModuleID, string TabID)
		{
			bool IsPortable = false;
			int parsedModuleID = 0;
			int parsedTabID = 0;

			bool validModuleID = int.TryParse(ModuleID, out parsedModuleID);
			bool validTabID = int.TryParse(TabID, out parsedTabID);

			if ((validModuleID && validTabID))
			{
				ModuleInfo moduleInfo = moduleCtrl.GetModule(parsedModuleID, parsedTabID);
				if (((moduleInfo != null)))
				{
					DesktopModuleInfo moduleDesktopInfo = moduleInfo.DesktopModule;
					if (((moduleDesktopInfo != null)))
					{
						IsPortable = moduleDesktopInfo.IsPortable;
					}
				}
			}

			return IsPortable;

		}

		private void LoadVisibilityList()
		{
			VisibilityLst.Enabled = !AddExistingModule.Checked;
			if ((VisibilityLst.Enabled))
			{
				Dictionary<string, string> items = new Dictionary<string, string>();
				items.Add("0", GetString("PermissionView"));
				items.Add("1", GetString("PermissionEdit"));

				VisibilityLst.Items.Clear();
				VisibilityLst.DataValueField = "key";
				VisibilityLst.DataTextField = "value";
				VisibilityLst.DataSource = items;
				VisibilityLst.DataBind();
			}
		}

		private void LoadPaneList()
		{
			PaneLst.Items.Clear();
			PaneLst.DataSource = PortalSettings.Current.ActiveTab.Panes;
			PaneLst.DataBind();
			if ((PortalSettings.Current.ActiveTab.Panes.Contains(DotNetNuke.Common.Globals.glbDefaultPane)))
			{
				PaneLst.SelectedValue = DotNetNuke.Common.Globals.glbDefaultPane;
			}
		}

		private void LoadPositionList()
		{
			Dictionary<string, string> items = new Dictionary<string, string>();
			items.Add("TOP", GetString("Top"));
			items.Add("ABOVE", GetString("Above"));
			items.Add("BELOW", GetString("Below"));
			items.Add("BOTTOM", GetString("Bottom"));

			PositionLst.Items.Clear();
			PositionLst.DataValueField = "key";
			PositionLst.DataTextField = "value";
			PositionLst.DataSource = items;
			PositionLst.DataBind();
			PositionLst.SelectedValue = "BOTTOM";
		}

		private void LoadPaneModulesList()
		{
			Dictionary<string, string> items = new Dictionary<string, string>();
			items.Add("", "");

			foreach (ModuleInfo m in PortalSettings.Current.ActiveTab.Modules)
			{
				//if user is allowed to view module and module is not deleted
				if (ModulePermissionController.CanViewModule(m) == true && m.IsDeleted == false)
				{
					//modules which are displayed on all tabs should not be displayed on the Admin or Super tabs
					if (m.AllTabs == false || PortalSettings.Current.ActiveTab.IsSuperTab == false)
					{
						if (m.PaneName == PaneLst.SelectedValue)
						{
						    int moduleOrder = m.ModuleOrder;

                            while (items.ContainsKey(moduleOrder.ToString()) || moduleOrder == 0)
                            {
                                moduleOrder++;
                            }
						    items.Add(moduleOrder.ToString(), m.ModuleTitle);
						}
					}
				}
			}

			PaneModulesLst.Enabled = true;
			PaneModulesLst.Items.Clear();
			PaneModulesLst.DataValueField = "key";
			PaneModulesLst.DataTextField = "value";
			PaneModulesLst.DataSource = items;
			PaneModulesLst.DataBind();

			if ((PaneModulesLst.Items.Count <= 1))
			{
				Telerik.Web.UI.RadComboBoxItem listItem = PositionLst.Items.FindItemByValue("ABOVE");
				if (((listItem != null)))
				{
					PositionLst.Items.Remove(listItem);
				}
				listItem = PositionLst.Items.FindItemByValue("BELOW");
				if (((listItem != null)))
				{
					PositionLst.Items.Remove(listItem);
				}
				PaneModulesLst.Enabled = false;
			}

			if ((PositionLst.SelectedValue == "TOP" || PositionLst.SelectedValue == "BOTTOM"))
			{
				PaneModulesLst.Enabled = false;
			}
		}

		private string LocalResourceFile
		{
			get { return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); }
		}

		private string GetString(string key)
		{
			return Localization.GetString(key, LocalResourceFile);
		}

		public bool CanAddModuleToPage()
		{
			if (HttpContext.Current == null)
			{
				return false;
			}
			//If we are not in an edit page
			return (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["mid"])) && (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ctl"]));
		}

		//todo: Move to business layer
		//todo: Return message when we try to add an existing module that has already been added to the page (we can't add the module twice)
		private void DoAddExistingModule(int moduleId, int tabId, string paneName, int position, string align)
		{
			ModuleController moduleCtrl = new ModuleController();
			ModuleInfo moduleInfo = moduleCtrl.GetModule(moduleId, tabId, false);

			if ((moduleInfo != null))
			{
				// clone the module object ( to avoid creating an object reference to the data cache )
				ModuleInfo newModule = moduleInfo.Clone();

				newModule.TabID = PortalSettings.Current.ActiveTab.TabID;
				newModule.ModuleOrder = position;
				newModule.PaneName = paneName;
				newModule.Alignment = align;
				moduleCtrl.AddModule(newModule);

				//Add Event Log
				int userID = -1;
				if (Request.IsAuthenticated)
				{
					UserInfo user = UserController.GetCurrentUserInfo();
					if (((user != null)))
					{
						userID = user.UserID;
					}
				}

				Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
				objEventLog.AddLog(newModule, PortalSettings.Current, userID, "", Services.Log.EventLog.EventLogController.EventLogType.MODULE_CREATED);
			}
		}

		//this has an overload of whether or not to create a cloned module
		private void DoAddExistingModule(int moduleId, int tabId, string paneName, int position, string align, bool cloneModule)
		{
			ModuleController moduleCtrl = new ModuleController();
			ModuleInfo moduleInfo = moduleCtrl.GetModule(moduleId, tabId, false);

			int userID = -1;
			if (Request.IsAuthenticated)
			{
				UserInfo user = UserController.GetCurrentUserInfo();
				if (((user != null)))
				{
					userID = user.UserID;
				}
			}


			if ((moduleInfo != null))
			{
				// clone the module object ( to avoid creating an object reference to the data cache )
				ModuleInfo newModule = moduleInfo.Clone();

                newModule.UniqueId = Guid.NewGuid(); // Cloned Module requires a different uniqueID

				newModule.TabID = PortalSettings.Current.ActiveTab.TabID;
				newModule.ModuleOrder = position;
				newModule.PaneName = paneName;
				newModule.Alignment = align;

				if ((cloneModule))
				{
					newModule.ModuleID = Null.NullInteger;
					//reset the module id
					newModule.ModuleID = moduleCtrl.AddModule(newModule);

					if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass))
					{
						object objObject = Framework.Reflection.CreateObject(newModule.DesktopModule.BusinessControllerClass, newModule.DesktopModule.BusinessControllerClass);
						if (objObject is IPortable)
						{
							string Content = Convert.ToString(((IPortable)objObject).ExportModule(moduleId));
							if (!string.IsNullOrEmpty(Content))
							{
								((IPortable)objObject).ImportModule(newModule.ModuleID, Content, newModule.DesktopModule.Version, userID);
							}
						}
					}

				}
				else
				{
					moduleCtrl.AddModule(newModule);
				}

				//Add Event Log
				Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
				objEventLog.AddLog(newModule, PortalSettings.Current, userID, "", Services.Log.EventLog.EventLogController.EventLogType.MODULE_CREATED);


			}
		}


		private void DoAddNewModule(string title, int desktopModuleId, string paneName, int position, int permissionType, string align)
		{
			TabPermissionCollection objTabPermissions = PortalSettings.Current.ActiveTab.TabPermissions;
			PermissionController objPermissionController = new PermissionController();
			ModuleController objModules = new ModuleController();
			Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
			int j = 0;

			try {
				DesktopModuleInfo desktopModule = null;
				if (!DesktopModuleController.GetDesktopModules(PortalSettings.Current.PortalId).TryGetValue(desktopModuleId, out desktopModule)) {
					throw new ArgumentException("desktopModuleId");
				}
			} catch (Exception ex) {
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
			}

			int UserId = -1;
			if (Request.IsAuthenticated) {
				UserInfo objUserInfo = UserController.GetCurrentUserInfo();
				UserId = objUserInfo.UserID;
			}

			foreach (ModuleDefinitionInfo objModuleDefinition in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values)
			{
				ModuleInfo objModule = new ModuleInfo();
				objModule.Initialize(PortalSettings.Current.PortalId);

				objModule.PortalID = PortalSettings.Current.PortalId;
				objModule.TabID = PortalSettings.Current.ActiveTab.TabID;
				objModule.ModuleOrder = position;
				if (string.IsNullOrEmpty(title)) {
					objModule.ModuleTitle = objModuleDefinition.FriendlyName;
				} else {
					objModule.ModuleTitle = title;
				}
				objModule.PaneName = paneName;
				objModule.ModuleDefID = objModuleDefinition.ModuleDefID;
				if (objModuleDefinition.DefaultCacheTime > 0) {
					objModule.CacheTime = objModuleDefinition.DefaultCacheTime;
					if (PortalSettings.Current.DefaultModuleId > Null.NullInteger && PortalSettings.Current.DefaultTabId > Null.NullInteger) {
						ModuleInfo defaultModule = objModules.GetModule(PortalSettings.Current.DefaultModuleId, PortalSettings.Current.DefaultTabId, true);
						if ((defaultModule != null)) {
							objModule.CacheTime = defaultModule.CacheTime;
						}
					}
				}

				switch (permissionType) {
					case 0:
						objModule.InheritViewPermissions = true;
						break;
					case 1:
						objModule.InheritViewPermissions = false;
						break;
				}

				// get the default module view permissions
				ArrayList arrSystemModuleViewPermissions = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW");

				// get the permissions from the page
				foreach (TabPermissionInfo objTabPermission in objTabPermissions) {
					if (objTabPermission.PermissionKey == "VIEW" && permissionType == 0) {
						//Don't need to explicitly add View permisisons if "Same As Page"
						continue;
					}

					// get the system module permissions for the permissionkey
					ArrayList arrSystemModulePermissions = objPermissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", objTabPermission.PermissionKey);
					// loop through the system module permissions
					for (j = 0; j <= arrSystemModulePermissions.Count - 1; j++) {
						// create the module permission
						PermissionInfo objSystemModulePermission = default(PermissionInfo);
						objSystemModulePermission = (PermissionInfo)arrSystemModulePermissions[j];
						if (objSystemModulePermission.PermissionKey == "VIEW" && permissionType == 1 && objTabPermission.PermissionKey != "EDIT") {
							//Only Page Editors get View permissions if "Page Editors Only"
							continue;
						}

						ModulePermissionInfo objModulePermission = AddModulePermission(objModule, objSystemModulePermission, objTabPermission.RoleID, objTabPermission.UserID, objTabPermission.AllowAccess);

						// ensure that every EDIT permission which allows access also provides VIEW permission
						if (objModulePermission.PermissionKey == "EDIT" && objModulePermission.AllowAccess) {
							ModulePermissionInfo objModuleViewperm = AddModulePermission(objModule, (PermissionInfo)arrSystemModuleViewPermissions[0], objModulePermission.RoleID, objModulePermission.UserID, true);
						}
					}

					//Get the custom Module Permissions,  Assume that roles with Edit Tab Permissions
					//are automatically assigned to the Custom Module Permissions
					if (objTabPermission.PermissionKey == "EDIT") {
						ArrayList arrCustomModulePermissions = objPermissionController.GetPermissionsByModuleDefID(objModule.ModuleDefID);

						// loop through the custom module permissions
						for (j = 0; j <= arrCustomModulePermissions.Count - 1; j++) {
							// create the module permission
							PermissionInfo objCustomModulePermission = default(PermissionInfo);
							objCustomModulePermission = (PermissionInfo)arrCustomModulePermissions[j];

							AddModulePermission(objModule, objCustomModulePermission, objTabPermission.RoleID, objTabPermission.UserID, objTabPermission.AllowAccess);
						}
					}
				}
                if (PortalSettings.Current.ContentLocalizationEnabled)
                {
                    Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId);
                    objModule.CultureCode = defaultLocale.Code;
                }
                else
                {
                    objModule.CultureCode = Null.NullString;
                }
			    objModule.AllTabs = false;
				objModule.Alignment = align;

				objModules.AddModule(objModule);
			}

		}

		private ModulePermissionInfo AddModulePermission(ModuleInfo objModule, PermissionInfo permission, int roleId, int userId, bool allowAccess)
		{
			ModulePermissionInfo objModulePermission = new ModulePermissionInfo();
			objModulePermission.ModuleID = objModule.ModuleID;
			objModulePermission.PermissionID = permission.PermissionID;
			objModulePermission.RoleID = roleId;
			objModulePermission.UserID = userId;
			objModulePermission.PermissionKey = permission.PermissionKey;
			objModulePermission.AllowAccess = allowAccess;

			// add the permission to the collection
			if (!objModule.ModulePermissions.Contains(objModulePermission))
			{
				objModule.ModulePermissions.Add(objModulePermission);
			}

			return objModulePermission;
		}
		#endregion

	}

}


